import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/pages/login/index.vue"),
    meta: { requiresAuth: false },
  },
  {
    path: "/index",
    name: "Index",
    component: () => import("@/pages/index/index.vue"),
    meta: { requiresAuth: true },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem("token");

  if (to.meta.requiresAuth && !isAuthenticated) {
    // 需要认证但未登录，重定向到登录页
    next("/login");
  } else if (to.path === "/login" && isAuthenticated) {
    // 已登录用户访问登录页，重定向到首页
    next("/index");
  } else {
    next();
  }
});

// 在路由配置中添加错误处理
router.onError((error) => {
  console.error("路由错误:", error);
});

// 添加全局后置钩子来检查页面加载
router.afterEach((to) => {
  console.log("页面加载完成:", to.path);
});

export default router;
